package com.opdar.plugins.mybatis.core;

import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.InputStreamResource;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by shiju on 2016/12/23.
 */
public class MapperResource extends AbstractResource {

    private final InputStream inputStream;

    private final String description;

    private boolean read = false;

    public MapperResource(InputStream inputStream) {
        this(inputStream, "resource loaded through InputStream");
    }

    public MapperResource(InputStream inputStream, String description) {
        if (inputStream == null) {
            throw new IllegalArgumentException("InputStream must not be null");
        }
        this.inputStream = inputStream;
        this.description = (description != null ? description : "");
    }

    @Override
    public boolean exists() {
        return true;
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public InputStream getInputStream() throws IOException, IllegalStateException {
        return this.inputStream;
    }

    @Override
    public String getDescription() {
        return "InputStream resource [" + this.description + "]";
    }


    /**
     * This implementation compares the underlying InputStream.
     */
    @Override
    public boolean equals(Object obj) {
        return (obj == this ||
                (obj instanceof MapperResource && ((MapperResource) obj).inputStream.equals(this.inputStream)));
    }

    /**
     * This implementation returns the hash code of the underlying InputStream.
     */
    @Override
    public int hashCode() {
        return this.inputStream.hashCode();
    }

}
